package com.briup.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.briup.common.bean.TblCustomer;
import com.briup.common.util.MyBatisSqlSessionFactory;
import com.briup.service.impl.TblCustomerServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/jsp/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username") ;
		String password = request.getParameter("password") ;
		boolean check = false ;
		SqlSession openSession = MyBatisSqlSessionFactory.openSession() ;
		TblCustomer customer = null ;
		try {
			TblCustomerServiceImpl tblCustomerServiceImpl = new TblCustomerServiceImpl() ;
			customer = tblCustomerServiceImpl.selectCustomerByNameAndPwd(openSession, username, password) ;
			if (customer == null) {
				request.getSession().setAttribute("msg", "用户名或密码错误！");
			}else {
				request.getSession().setAttribute("user", customer);
				check = true ;
			}
		}catch (Exception e) {
			e.printStackTrace();
			
		}finally {
			openSession.close();
			if (!check) {
				response.sendRedirect("login.jsp");
			}else{
				response.sendRedirect("manager/home.jsp");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
